<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
				<el-select v-model="state.tableData.param.company_id" multiple filterable placeholder="请选择所属公司" clearable
					size="default" style="width: 180px;">
					<el-option v-for="(item, index) in state.platsData.company" :key="item.id" :label="item.title"
						:value="item.id"></el-option>
				</el-select>
				<el-date-picker size="default" style="width: 280px;" v-model="state.tableData.param.time"
					type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
					:default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]" value-format='X' />
				<el-button size="default" type="primary" @click="onHandleCurrentChange(1)">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
			</div>
			<el-table :data="state.tableData.data" border v-loading="state.tableData.loading" style="width: 100%"
				:header-cell-style="headerCellStyle" :span-method="objectSpanMethod">
				<el-table-column prop="time" align="center" label="日期">
					<template #default="scope">
						<div v-if="scope.row.isGroupFirstRow">
							{{ scope.row.time }} ({{ scope.row.dateStat.total }})
              <div style="display: flex;flex-direction: column;align-items: center;">
								<el-tag type="success" size="small" style="margin-top: 5px"> 积分: {{
									scope.row.dateStat.total_pay }} </el-tag>
								<el-tag type="success" size="small" style="margin-top: 5px"> 平均积分: {{
									scope.row.dateStat.avg_pay }} </el-tag>
								<el-tag type="danger" size="small" style="margin-top: 5px"> 核减积分: {{
									scope.row.dateStat.nuclear_pay }} </el-tag>
								<el-tag type="danger" size="small" style="margin-top: 5px"> 平均核减: {{
									scope.row.dateStat.avg_nuclear_pay }} </el-tag>
							</div>
						</div>
						<div v-else>
							{{ scope.row.time }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="公司名称">
					<template #default="scope">
						<div v-if="scope.row.isGroupFirstRow"
							style="display: flex;flex-direction: column;align-items: center;">
							<div class="font-bold">{{ scope.row.company_name }}({{ scope.row.dateStat.companyCount }})</div>
							<div style="display: flex;flex-direction: column;align-items: center;">
								<el-tag type="success" size="small" style="margin-top: 5px; cursor: pointer"> 数量: {{
									scope.row.group_summary.total_count }} </el-tag>
								<el-tag type="success" size="small" style="margin-top: 5px"> 积分: {{
									scope.row.group_summary.total_pay }} </el-tag>
								<el-tag type="success" size="small" style="margin-top: 5px"> 平均积分: {{
									scope.row.group_summary.avg_pay }} </el-tag>	
								<el-tag type="danger" size="small" style="margin-top: 5px"> 核减数: {{
									scope.row.group_summary.nuclear_count }} </el-tag>
								<el-tag type="danger" size="small" style="margin-top: 5px"> 核减积分: {{
									scope.row.group_summary.nuclear_pay }} </el-tag>
								<el-tag type="danger" size="small" style="margin-top: 5px"> 平均核减: {{
									scope.row.group_summary.avg_nuclear_pay }} </el-tag>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="user_name" align="center" label="用户名"></el-table-column>
				<el-table-column prop="nickname" align="center" label="昵称"></el-table-column>
				<el-table-column prop="total_count" align="center" label="数量"></el-table-column>
				<el-table-column prop="total_pay" align="center" label="积分"></el-table-column>
				<el-table-column prop="nuclear_count" align="center" label="核减数"></el-table-column>
				<el-table-column prop="nuclear_pay" align="center" label="核减积分"></el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<script setup name="memberReport">
import { reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { commApi } from '/@/api/comm/index';
const headerCellStyle = {
	backgroundColor: 'rgb(225 225 225)', // 背景色加深
}
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			time: null,
			company_id: []
		},
	},
	platsData: {
		company: [],
		palt: [],
		paltform: []
	},
});

const processGroupSummary = () => {
  // 先按日期+公司排序
  state.tableData.data.sort((a, b) => {
    if (a.time !== b.time) return a.time - b.time;
    return a.company_name.localeCompare(b.company_name);
  });

  // 按日期分组统计
  const dateGroup = new Map();
  state.tableData.data.forEach(row => {
    const dateKey = row.time;
    if (!dateGroup.has(dateKey)) {
      dateGroup.set(dateKey, {
        count: 0,
        companies: new Map(),
        total_pay: 0,
        total_nuclear_pay: 0,
      });
    }
    const dateStat = dateGroup.get(dateKey);
    dateStat.count++; // 日期总数量加1
    dateStat.total_pay += Number(row.total_pay) || 0;
    dateStat.total_nuclear_pay += Number(row.nuclear_pay) || 0;

    // 按公司分组统计
    const companyKey = row.company_name;
    if (!dateStat.companies.has(companyKey)) {
      dateStat.companies.set(companyKey, 0);
    }
    dateStat.companies.set(companyKey, dateStat.companies.get(companyKey) + 1);
  });

  // 按日期+公司分组统计
  const groupMap = new Map();
  state.tableData.data.forEach(row => {
    const groupKey = `${row.time}-${row.company_name}`;
    if (!groupMap.has(groupKey)) {
      groupMap.set(groupKey, {
        total_count: 0,
        total_pay: 0,
        nuclear_count: 0,
        nuclear_pay: 0,
        count: 0,
        avg_pay: 0,
        avg_nuclear_pay: 0,
      });
    }
    const summary = groupMap.get(groupKey);
    summary.total_count += Number(row.total_count) || 0;
    summary.total_pay += Number(row.total_pay) || 0;
    summary.nuclear_count += Number(row.nuclear_count) || 0;
    summary.nuclear_pay += Number(row.nuclear_pay) || 0;
    summary.count++;
    summary.avg_pay = (summary.total_pay / summary.count).toFixed(2);
    summary.avg_nuclear_pay = (summary.nuclear_pay / summary.count).toFixed(2);
  });

  const groupFirstRowIndex = new Map();
  state.tableData.data.forEach((row, index) => {
    const groupKey = `${row.time}-${row.company_name}`;
    if (!groupFirstRowIndex.has(groupKey)) {
      groupFirstRowIndex.set(groupKey, index);
      row.group_summary = groupMap.get(groupKey);
      row.isGroupFirstRow = true;
      
      // 附加日期统计信息到行数据
      if (dateGroup.has(row.time)) {
        const dateStat = dateGroup.get(row.time);
        row.dateStat = {
          total: dateStat.count,
          total_pay: dateStat.total_pay,
          total_nuclear_pay: dateStat.total_nuclear_pay,
          companyCount: dateStat.companies.get(row.company_name),
          avg_pay: (dateStat.total_pay / dateStat.count).toFixed(2),
          avg_nuclear_pay: (dateStat.total_nuclear_pay / dateStat.count).toFixed(2),
        };
      }
    } else {
      row.isGroupFirstRow = false;
    }
  });
};

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 处理日期列合并（columnIndex === 0）
  if (columnIndex === 0) {
    const key = `date-${row.time}`; // 日期分组键
    let startIndex = 0;
    let count = 0;
    for (let i = 0; i < state.tableData.data.length; i++) {
      const itemKey = `date-${state.tableData.data[i].time}`;
      if (itemKey === key) {
        if (count === 0) startIndex = i;
        count++;
      }
    }
    if (rowIndex === startIndex) {
      return { rowspan: count, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }

  // 处理公司名列合并（columnIndex === 1）
  if (columnIndex === 1) {
    const key = `${row.time}-${row.company_name}`; // 日期+公司分组键
    let startIndex = 0;
    let count = 0;
    for (let i = 0; i < state.tableData.data.length; i++) {
      const itemKey = `${state.tableData.data[i].time}-${state.tableData.data[i].company_name}`;
      if (itemKey === key) {
        if (count === 0) startIndex = i;
        count++;
      }
    }
    if (rowIndex === startIndex) {
      return { rowspan: count, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }

  // 其他列不合并
  return { rowspan: 1, colspan: 1 };
};

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	commApi().getCompanyList(state.tableData.param).then(res => {
		state.tableData.data = res.data;
		// 预处理公司汇总数据
		processGroupSummary();
	}).finally(() => {
		state.tableData.loading = false;
	})
};
// 分页改变
const onHandleCurrentChange = (val) => {
	getTableData();
};
// 初始化公司数据
const getCompanyData = () => {
	commApi().getPlats({ paltform_type: 3 }).then(res => {
		state.platsData = res.data
	})
};
// 页面加载时
onMounted(() => {
	getTableData();
	getCompanyData()
});
</script>

<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;

		.el-table {
			flex: 1;
		}
	}
}
</style>
